<?php

/**
 * Message wrapper
 * @package Nina
 * @author John Main <john@thedaddy.org>
 */

class Nina_Message
{
	/**
	 * Constructor
	 */
	public function __construct() {
		if(!isset($_SESSION['nina_messages']))
			$_SESSION['nina_messages'] = array();
	}

	/**
	 * Add a message
	 * @param string|array $message The message(s)
	 * @param string [$anchor='default'] The message anchor
	 */
	public function add($message, $anchor = 'default') {
		if(!isset($_SESSION['nina_messages'][$anchor]))
			$_SESSION['nina_messages'][$anchor] = array();

		if(is_array($message))
			$_SESSION['nina_messages'][$anchor] = array_merge($_SESSION['nina_messages'][$anchor], $message);
		elseif(!in_array($message, $_SESSION['nina_messages'][$anchor]))
			$_SESSION['nina_messages'][$anchor][] = $message;
	}

	/**
	 * Static add a message
	 * @param string|array $message The message(s)
	 * @param string [$anchor='default'] The message anchor
	 */
	public static function doAdd($message, $anchor = 'default') {
		$message_obj = new self();
		$message_obj->add($message, $anchor);
	}

	/**
	 * Get all messages
	 * @param string [$anchor='default'] The message anchor
	 * @param boolean [$clear=true] Clear the messages after reading them
	 * @return array
	 */
	public function get($anchor = 'default', $clear = true) {
		if(isset($_SESSION['nina_messages'][$anchor])) {
			$messages = $_SESSION['nina_messages'][$anchor];

			if($clear)
				$_SESSION['nina_messages'][$anchor] = array();

			return $messages;
		}
		else
			return array();
	}

	/**
	 * Static get all messages
	 * @param string [$anchor='default'] The message anchor
	 * @param boolean [$clear=true] Clear the messages after reading them
	 * @return array
	 */
	public static function doGet($anchor = 'default', $clear = true) {
		$message_obj = new self();
		$message_obj->get($anchor, $clear);
	}

	/**
	 * Get first message
	 * @param string [$anchor='default'] The message anchor
	 * @param boolean [$clear=true] Clear the messages after reading them
	 * @return string
	 */
	public function getFirst($anchor = 'default', $clear = true) {
		if(isset($_SESSION['nina_messages'][$anchor])) {
			if($clear)
				return array_shift($_SESSION['nina_messages'][$anchor]);
			else
				return $_SESSION['nina_messages'][$anchor][0];
		}
		else
			return '';
	}

	/**
	 * Get default messages
	 * @return array
	 */
	public function getDefault() {
		return $this->get();
	}

	/**
	 * Check if any messages are present
	 * @param string [$anchor='default'] The message anchor
	 * @return boolean
	 */
	public function hasMessages($anchor = 'default') {
		if(isset($_SESSION['nina_messages'][$anchor]))
			return !empty($_SESSION['nina_messages'][$anchor]);
		else
			return false;
	}

	/**
	 * Clear the messages
	 */
	public function clear() {
		$_SESSION['nina_messages'] = array();
	}
}
